<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目状态" prop="projectStatus">
          <el-select placeholder="请选择项目状态" v-model="queryParams.projectStatus" size="small">
            <el-option label="未开始" value="1"></el-option>
            <el-option label="进行中" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
            <el-option label="已取消" value="4"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="dateValue">
        <el-date-picker
          v-model="queryParams.dateValue"
          type="daterange"
          align="right"
          size="small"
          unlink-panels
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:project:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="name" >
        <template slot-scope="scope">
          <span style="color:  #1c84c6;cursor: pointer" @click="goDetail(scope.row)" v-hasPermi="['biz:project:query']">{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目金额(陪护豆/个)" align="center" prop="price" />
      <el-table-column label="项目人员" align="center" prop="memberCount" />
      <el-table-column label="项目进度" align="center" prop="schedule" >
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="15" :percentage="scope.row.schedule"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="项目开始时间" align="center" prop="projectStartTime" width="180"/>
      <el-table-column label="项目结束时间" align="center" prop="projectEndTime" width="180"/>
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="状态" align="center" prop="projectStatus">
        <template slot-scope="scope">
          <span v-html="statusFormatter(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.status==='inactive'"
              size="mini"
              type="text"
              icon="el-icon-check"
              style="color: #4AB7BD"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['biz:project:changeStatus']"
          >启用
          </el-button>
          <el-button
              v-if="scope.row.status==='active'"
              size="mini"
              type="text"
              icon="el-icon-close"
              style="color: #E65D6E"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['biz:project:changeStatus']"
          >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="new Date(scope.row.projectStartTime) > new Date()"
            v-hasPermi="['biz:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleFinish(scope.row)"
            v-if="(new Date(scope.row.projectStartTime) < new Date() && new Date(scope.row.projectEndTime) > new Date()) && scope.row.realEndTime == null"
            v-hasPermi="['biz:project:finish']"
          >结束活动</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-delete"
            @click="handleCancel(scope.row)"
            v-if="new Date(scope.row.projectStartTime) > new Date()"
            v-hasPermi="['biz:project:cancel']"
          >取消</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAudit(scope.row)"
            v-if="(new Date(scope.row.projectEndTime) < new Date() || scope.row.realEndTime != null) && scope.row.auditStatus === '0'"
            v-hasPermi="['biz:project:audit']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学研项目对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="45%"
      :show-close="true"
      :wrapperClosable="false"
      :before-close="closeDrawer"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-left: 15px">
        <el-form-item label="项目图片" prop="image">
          <el-upload
            class="avatar-uploader"
            accept="image/jpeg,image/png,image/jpg"
            :action="upload.url"
            name="multipartFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="color: red">推荐上传jpg、png、jpeg文件，且不超过1MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" maxlength="100" placeholder="请输入项目名称" style="width: 50%"/>
        </el-form-item>
        <el-form-item label="项目金额" prop="price">
          <el-input v-model="form.price" maxlength="10,2" placeholder="请输入项目金额" oninput ="value=value.replace(/[^0-9.]/g,'')" style="width: 50%">
            <template slot="append">陪护豆</template>
          </el-input>
        </el-form-item>
        <el-form-item label="项目时间" prop="dateValue" >
          <el-date-picker
            style="width: 50%"
            v-model="form.dateValue"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="imageArr" label="轮播图片">
          <el-upload
            :action="upload.url"
            name = "multipartFile"
            multiple
            :limit="uploadSize"
            list-type="picture-card"
            :file-list="fileList"
            :on-exceed="handleUploadExceed"
            :with-credentials='true'
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择所属医院" style="width: 50%" >
            <el-option
              v-for="item in hospitalList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" placeholder="请输入排序"  :min="1" style="width: 50%"></el-input-number>
        </el-form-item>
        <el-form-item label="项目介绍" prop="introduction">
<!--          <UEditor  :editor-content="form.introduction"  @updateContent="val => {this.form.introduction = val;}"/>-->
          <Editor v-model="form.introduction" style="height: 300px"/>
        </el-form-item>
        <el-form-item label="项目成员" style="margin-top: 70px">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleSelectMember"
          >关联成员</el-button>
          <el-table  :data="doctorList"  :key="key" style="margin-top: 15px;width: 100%">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="名称" align="center" prop="nickName" />
            <el-table-column label="职级" align="center" prop="level" />
            <el-table-column label="科室" align="center" prop="departmentName" />
            <el-table-column label="所属医院" align="center" prop="hospitalName"/>
          </el-table>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="submitForm">确 认</el-button>
<!--        <el-button @click="stockCancel">取 消</el-button>-->
      </div>
    </el-drawer>

    <el-drawer
      title="项目详情"
      :visible.sync="detailOpen"
      size="45%"
      :show-close="true"
      append-to-body>
      <div style="margin: 20px 20px">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="baseInfo">
            <el-form ref="form" :model="form" label-width="140px" size="mini">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目图片：">
                    <el-image :src="form.image" style="width: 140px;height: 130px"
                              :preview-src-list="new Array(form.image)"></el-image>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目名称：">{{form.name}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目金额(陪护豆)：" style="color: #1c84c6">{{form.price}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目开始时间：">{{form.projectStartTime}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目结束时间：">{{form.projectEndTime}}</el-form-item>
                </el-col>
                <el-col :span="24" >
                  <el-form-item label="实际结束时间：" v-if="form.realEndTime">{{form.realEndTime}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="募集金额(陪护豆)：" style="color: #1c84c6">{{form.raisedAmount === null ? 0 : form.raisedAmount}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="项目进度：">
                    <el-progress :text-inside="false" :stroke-width="16" :percentage="form.schedule" style="width: 300px"></el-progress>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="创建时间：">{{parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="项目介绍" name="introduction">
            <span v-html="form.introduction"></span>
          </el-tab-pane>
          <el-tab-pane label="项目成员" name="projectMember">
            <el-table ref="multipleTable"  :data="form.doctorList">
              <el-table-column label="序号" align="center" type="index"/>
              <el-table-column label="名称" align="center" prop="nickName" />
              <el-table-column label="职级" align="center" prop="level" />
              <el-table-column label="科室" align="center" prop="departmentName" />
              <el-table-column label="医院" align="center" prop="hospitalName" />
              <el-table-column label="分配方式" align="center" prop="allocation" v-if="form.auditStatus === '1'">
                <template slot-scope="scope">
                  <span v-if="scope.row.allocation === '1'">按金额</span>
                  <span v-if="scope.row.allocation === '2'">按比例</span>
                </template>
              </el-table-column>
              <el-table-column label="分配金额" align="center" prop="distributeScale" v-if="form.allocation === '1'"/>
              <el-table-column label="分配比例" align="center" prop="distributeScale" v-if="form.allocation === '2'">
                 <template slot-scope="scope">
                   <span>{{scope.row.distributeScale}}%</span>
                 </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="赞助明细" name="sponsorDetail">
            <el-form :model="sponsorQueryParams" ref="sponsorQueryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
              <el-form-item label="用户名称" prop="userName">
                <el-input
                  v-model="sponsorQueryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  @keyup.enter.native="handleSponsorQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleSponsorQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetSponsorQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table v-loading="sponsorLoading" :data="sponsorList">
              <el-table-column label="序号" align="center" type="index"/>
              <el-table-column label="用户" align="center" prop="userName"/>
              <el-table-column label="手机号" align="center" prop="phone"/>
              <el-table-column label="赞助金额(陪护豆/个)" align="center" prop="sponsorAmount"/>
              <el-table-column label="备注" align="center" prop="remark"/>
            </el-table>
            <pagination
              v-show="sponsorTotal>0"
              :total="sponsorTotal"
              :page.sync="sponsorQueryParams.pageNum"
              :limit.sync="sponsorQueryParams.pageSize"
              @pagination="getSponsorList"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>




    <el-dialog title="选择医生" :visible.sync="doctorOpen" width="800px" append-to-body :show-close="false">
      <el-form :model="doctorQueryParams" ref="doctorQueryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="医生名称" prop="nickName">
          <el-input
            v-model.trim="doctorQueryParams.nickName"
            placeholder="请输入医生名称"
            clearable
            size="small"
            @keyup.enter.native="handleDoctorQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  size="mini" @click="handleDoctorQuery">搜索</el-button>
          <el-button  size="mini" @click="resetDoctorQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="multipleTable" v-loading="doctorLoading" :data="allDoctorList" :row-key="getRowKeys" @selection-change="handleSelectionChangeByProduct">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
        <el-table-column label="名称" align="center" prop="nickName" />
        <el-table-column label="职级" align="center" prop="level" />
        <el-table-column label="科室" align="center" prop="departmentName" />
        <el-table-column label="医院" align="center" prop="hospitalName" />
      </el-table>
      <pagination
        v-show="doctorTotal>0"
        :total="doctorTotal"
        :page.sync="doctorQueryParams.pageNum"
        :limit.sync="doctorQueryParams.pageSize"
        @pagination="getAllDoctorList"
      />
      <div style="margin-top: 50px;text-align: center" >
        <el-button type="primary" @click="saveDoctor">确 定</el-button>
        <el-button @click="doctorCancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-drawer
      title="项目审核"
      :visible.sync="auditOpen"
      size="55%"
      :show-close="true"
      append-to-body>
      <el-form ref="form" :model="form"  :rules="rules"label-width="130px" size="mini">
<!--        <el-row>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="募集金额：">{{form.raisedAmount}}陪护豆</el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

        <el-form-item label="募集金额：" prop="raisedAmount">{{form.raisedAmount}} 陪护豆</el-form-item>
        <el-form-item label="分配方式：" prop="allocation">
          <el-radio v-model="form.allocation" label="1" @change="clean">按金额</el-radio>
          <el-radio v-model="form.allocation" label="2" @change="clean">按比例</el-radio>
        </el-form-item>
        <el-table  :data="doctorList"  :key="key1"   style="margin-top: 15px;">
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column label="名称" align="center" prop="nickName" />
          <el-table-column label="职级" align="center" prop="level" />
          <el-table-column label="科室" align="center" prop="departmentName" />
          <el-table-column label="所属医院" align="center" prop="hospitalName"/>
          <el-table-column label="分配比例(%)" align="center" prop="distributeScale" v-if="form.allocation === '2'">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.distributeScale"
                controls-position="right"
                :min="0"
                :max="100"
                @input.native="onInput0_100"
                style="width: 90%"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="分配金额" align="center" prop="distributeScale" v-if="form.allocation === '1'">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.distributeScale"
                controls-position="right"
                :min="0"
                :max="form.raisedAmount"
                style="width: 90%"
                @input.native="onInputAmount"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right;" v-if="totalAmount !== 0">
          <h3 style="margin-right: 30px">总计:{{totalAmount}}陪护豆</h3>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="auditSubmitForm" style="margin-top: 15px">确认审核</el-button>
          <el-button @click="auditCancel">取 消</el-button>
        </div>

      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, changeStatus,cancel,audit,finish } from "@/api/biz/project";
import { listAllDoctor} from "@/api/biz/doctorUser";
import { listAllHospital } from "@/api/biz/hospital";
import { listSponsor} from "@/api/biz/sponsor";
import { getToken } from "@/utils/auth";
import UEditor from '@/components/UEditor'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: "Project",
  components: {
    UEditor,
    ElImageViewer
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList:[],
      uploadSize:9,
      activeName: 'baseInfo',
      // 遮罩层
      loading: true,
      doctorLoading:true,
      sponsorLoading:true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      singleByDoctor: true,
      // 非多个禁用
      multiple: true,
      multipleByDoctor:true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      doctorTotal: 0,
      sponsorTotal: 0,
      // 学研项目表格数据
      projectList: [],
      sponsorList: [],
      doctorList:[],
      allDoctorList:[],
      hospitalList: [],
      key:0,
      key1:0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailOpen:false,
      doctorOpen: false,
      auditOpen:false,
      totalAmount:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        image: undefined,
        introduction: undefined,
        price: undefined,
        projectStartTime: undefined,
        projectEndTime: undefined,
        memberCount: undefined,
        schedule: undefined,
        sort: undefined,
        projectStatus: undefined,
        dateValue: undefined,
        startTime: undefined,
        endTime: undefined,
      },
      // 查询参数
      sponsorQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId:undefined,
        userName:undefined,
      },

      doctorQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userType: '40',
        nickName:null,
        hospitalId:undefined,
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadObs"
      },
      // 表单参数
      form: {},
      submitLoading: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        image: [
          { required: true, message: "项目图片不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "项目金额不能为空", trigger: "blur" }
        ],
        dateValue: [
          { required: true, message: "项目时间不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        introduction: [
          { required: true, message: "项目介绍不能为空", trigger: "blur" }
        ],
        doctorList: [
          { required: true, message: "请关联项目成员", trigger: "blur" }
        ],
        allocation: [
          { required: true, message: "请选择分配方式", trigger: "blur" }
        ],
        hospitalId: [
          { required: true, message: "请选择所属医院", trigger: "blur" }
        ],
        imageArr: [
          { required: true, message: "轮播图片不能为空", trigger: "blur" }
        ],
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  created() {
    this.getList();
    this.getAllHospitalList();
  },
  methods: {
    statusFormatter(row){
      if(row.projectStatus === '4'){
        return "<span style='color: red'>已取消</span>";
      }else if(row.realEndTime !=null){
        return "<span style='color: red'>已结束</span>";
      }else {
        if(new Date(row.projectStartTime) > new Date()){
          return "<span style='color: #00afff'>未开始</span>";
        }else if(new Date(row.projectEndTime) < new Date()){
          return "<span style='color: red'>已结束</span>";
        }else if(new Date(row.projectStartTime) < new Date() && new Date(row.projectEndTime) > new Date()){
          return  "<span style='color: green'>进行中</span>";
        }
      }
    },

    onInput0_100(e) {
      // this.$message.closeAll();
      // 验证是否是纯数字
      let isNumber = /^\d*$/.test(e.target.value);
      // 过滤非数字
      e.target.value = e.target.value.replace(/\D/g, "");
      if (!isNumber || e.target.value < 0 || e.target.value > 100) {
        this.$modal.msgError("只能输入[0,100]区间的整数");
        return;
      }

      e.target.value = (e.target.value >= 0 && e.target.value <= 100 && e.target.value.match(/^\d*/g)[0]) || null;
    },
    onInputAmount(e){
      // 验证是否是纯数字
      let isNumber = /^\d*$/.test(e.target.value);
      // 过滤非数字
      e.target.value = e.target.value.replace(/\D/g, "");
      if (!isNumber || e.target.value < 0 || e.target.value > this.form.raisedAmount) {
        this.$modal.msgError("只能输入[0,"+this.form.raisedAmount+"]区间的整数");
        return;
      }
      e.target.value = (e.target.value >= 0 && e.target.value <= this.form.raisedAmount && e.target.value.match(/^\d*/g)[0]) || null;
      this.key++;
    },
    clean(value){
     this.totalAmount = 0;
     this.doctorList.forEach(item =>{
      item.distributeScale = undefined;
     })
    },

    getRowKeys(row) {
      return row.userId;
    },
    /** 查询学研项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllHospitalList(){
      listAllHospital().then(res =>{
        console.log("res",res);
        this.hospitalList = res.data;
      });
    },
    /** 查询学研项目赞助列表 */
    getSponsorList() {
      this.sponsorLoading = true;
      listSponsor(this.sponsorQueryParams).then(response => {
        this.sponsorList = response.rows;
        this.sponsorTotal = response.total;
        this.sponsorLoading = false;
      });
    },
    getAllDoctorList(){
      this.doctorLoading = true;
      listAllDoctor(this.doctorQueryParams).then(res => {
        this.allDoctorList = res.rows;
        this.doctorTotal = res.total;
        this.doctorLoading = false;
        if(this.doctorList.length > 0){
          this.doctorList.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    auditCancel(){
      this.auditOpen = false;
      this.doctorList = undefined;
      this.reset();
    },
    getIndex($index) {
      //表格序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        image: null,
        introduction: null,
        price: null,
        projectStartTime: null,
        projectEndTime: null,
        memberCount: null,
        schedule: null,
        sort: null,
        projectStatus: "0",
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        dateValue:null,
        hospitalId:null,
        imageArr:[],
      };
      this.resetForm("form");
    },
    doctorCancel(){
      this.doctorOpen = false;
    },
    saveDoctor(){
      this.doctorOpen = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSponsorQuery() {
      this.sponsorQueryParams.pageNum = 1;
      this.getSponsorList();
    },
    handleDoctorQuery(){
      this.doctorQueryParams.pageNum = 1;
      this.getAllDoctorList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetDoctorQuery() {
      this.resetForm("doctorQueryForm");
      this.handleDoctorQuery();
    },
    resetSponsorQuery() {
      this.resetForm("sponsorQueryForm");
      this.handleSponsorQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSelectionChangeByProduct(selection) {
      console.log("selection",selection)
      this.doctorList = selection;
      this.singleByDoctor = selection.length!==1
      this.multipleByDoctor = !selection.length
      console.log("this.doctorList",this.doctorList)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = [];
      this.doctorList = [];
      this.reset();
      this.open = true;
      this.title = "添加学研项目";
    },
    handleChangeStatus(row) {
      let statusText = row.status === 'active' ? '禁用' : '启用'
      let status = row.status === 'active' ? 'inactive' : 'active'
      const ids = [row.id] || this.ids;
      this.$confirm('是否确认' + statusText + '该项数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeStatus({ids: ids, status: status});
      }).then(() => {
        this.getList();
        this.msgSuccess("操作成功");
      }).catch(function () {
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = [];
      this.reset();
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data;
        this.doctorList = this.form.doctorList;
        this.form.imageArr = [];
        if(this.form.images){
          this.form.imageArr =  JSON.parse(this.form.images);
          for (let i = 0; i <this.form.imageArr.length ; i++) {
            this.fileList.push(
              {
                "url":this.form.imageArr[i]
              }
            )
          }
        }
        this.open = true;
        this.title = "修改学研项目";
      });
    },
    handleAudit(row){
      this.reset();
      const id = row.id || this.ids
      this.doctorList = [];
      getProject(id).then(response => {
        this.form = response.data;
        this.doctorList = this.form.doctorList;
        this.auditOpen = true;
      });
    },
    goDetail(row){
      this.activeName = 'baseInfo';
      this.reset();
      this.form.doctorList = undefined;
      getProject(row.id).then(response => {
        this.form = response.data;
        this.doctorList = this.form.doctorList;
        this.detailOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.doctorList.length === 0){
            this.$modal.msgError("请至少选择一位项目成员");
            return;
          }
          this.form.doctorList = this.doctorList;
          console.log("this.form",this.form);
          this.submitLoading = true
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.submitLoading = false;
              this.getList();
            }).catch(() => {
              this.submitLoading = false;
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.submitLoading = false;
              this.getList();
            }).catch(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },
    /** 提交按钮 */
    auditSubmitForm() {
      console.log("form=",this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          let totalAmount = 0;
          let totalScale = 0;
          try{
            let text = this.form.allocation === '1' ? '分配金额': '分配比例';
            this.form.doctorList.forEach(item =>{
              if(item.distributeScale === null || item.distributeScale === undefined){
                throw new Error("用户名称："+item.nickName +"的"+text+"不能为空！");
              }
              if(this.form.allocation === '1'){
                totalAmount = totalAmount + item.distributeScale;
              }else if(this.form.allocation === '2'){
                totalScale = totalScale + item.distributeScale;
              }

            });
          }catch(e){
            this.$modal.msgError(e.toString().replace("Error:",""));
            return;
          };
          this.submitLoading = true
          if(this.form.allocation === '1' && totalAmount > this.form.raisedAmount){
            this.$modal.msgError("分配金额不能大于募集金额");
            return;
          }else if(this.form.allocation === '2' && totalScale > 100){
            this.$modal.msgError("分配比例不能大于100%");
            return;
          }
          console.log("this.from",this.form)
          audit(this.form).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.submitLoading = false;
            this.getList();
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学研项目编号为"' + ids + '"的数据项？').then(function() {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 结束活动操作 */
    handleFinish(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认提前结束学研项目名称为"' + row.name + '"的数据项？').then(function() {
        return finish(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("活动已结束");
      }).catch(() => {});
    },
    handleSelectMember(){
      if(!this.form.hospitalId){
        this.$modal.msgError("请先选择医院");
        return;
      }
      this.doctorQueryParams.hospitalId = this.form.hospitalId;
      this.getAllDoctorList();
      this.doctorOpen = true;
    },
    handleCancel(row){
      const ids = row.id || this.ids;
      let data = {
        id:row.id,
        projectStatus:'4',
      }
      this.$modal.confirm('是否确认取消学研项目名称为"' + row.name + '"的数据项？').then(function() {
        return cancel(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('biz/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    closeDrawer(){
      this.fileList = [];
      this.open = false
      this.reset()
    },
    handleAvatarSuccess(res, file) {
      this.form.image = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isLt2M;
    },
    handleAvatarSuccess2(res, file,fileList) {
      this.form.imageArr.push(res.data.url);
    },
    handleClick(value){
      if(this.activeName === 'sponsorDetail'){
          this.sponsorQueryParams.projectId = this.form.id;
          this.getSponsorList();
      }
    },
    handlePictureCardPreview(file) {//预览
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleError(err, file, fileList){//上传失败
      console.log(err)
    },
    handleUploadExceed(){
      this.$message.warning("最多上传:"+this.uploadSize + "张图片");
    },
    handleRemove(file, fileList) {//移除
      console.log("file", file);
      console.log("fileList", fileList);
      if(file.name){
        this.form.imageArr= this.form.imageArr.filter((x) => x !== file.response.data.url);
      }else {
        this.form.imageArr= this.form.imageArr.filter((x) => x !== file.url);
      }
    },
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
